<template>
	<input placeholder="请输入账号" v-model="zhanghao">
	<input placeholder="请输入密码" v-model="password" type="password">
	<button @click="login">登录</button>
	<button @click="reg">注册</button>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import {
		useUserStore
	} from '../../stores/user';

	let zhanghao = ref('');
	let password = ref('');
	let userStore = useUserStore();

	function reg() {
		uni.request({
			url: 'http://47.94.6.186:3001/api/user/reg',
			method: 'POST',
			data: {
				loginname: zhanghao.value,
				password: password.value
			}
		}).then(res => {
			console.log(res);
			uni.showToast({
				title: '注册成功',
				icon: 'success'
			});
		})
	}

	function login() {
		uni.request({
			url: 'http://47.94.6.186:3001/api/user/login',
			method: 'POST',
			data: {
				loginname: zhanghao.value,
				password: password.value
			}
		}).then(res => {
			console.log(res);
			uni.setStorageSync('token', res.data.data.token);
			uni.setStorageSync('userId', res.data.data.userid);
			userStore.saveLoginData({
				userInfo: {
					userid: res.data.data.userid,
					loginname: zhanghao.value,
					password: password.value
				}
			});

			// 登录成功后跳转到首页
			uni.switchTab({
				url: '/pages/index/index'
			});
		});
	}
</script>

<style scoped>
	input {
		width: 80%;
		margin: 20rpx auto;
		height: 80rpx;
		border: 1rpx solid #ddd;
		border-radius: 10rpx;
		padding: 0 20rpx;
	}

	button {
		width: 80%;
		margin: 20rpx auto;
		height: 80rpx;
		background-color: #007aff;
		color: white;
		border-radius: 10rpx;
	}
</style>